package cn.hl.hm.controller.manage;

import cn.hl.hm.logic.manage.RechargeRecoardOfflineLogic;
import cn.hl.hm.util.ExportData;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.Result;
import cn.hl.hm.util.paging.PageInfo;
import cn.hl.hm.vo.RechargeRecoardOfflineVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配载费提现审核功能
 * Created by xianghan on 17/12/26.
 */
@Controller
@RequestMapping("/manage/rechargeOffline")
public class RechargeRecoardOfflineController {
    private static final Logger logger = LoggerFactory.getLogger(RechargeRecoardOfflineController.class);
    @Autowired
    private RechargeRecoardOfflineLogic rechargeRecoardOfflineLogic;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@RequestParam String userPhone,
                      @RequestParam String plateNumber, @RequestParam BigDecimal amount,
                      @RequestParam Integer payType, @RequestParam Integer rechargeAdminId,
                      @RequestParam Integer roadFeeCollectorId,
                      HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("运营管理---新增线下配载费---/manage/rechargeOffline/add");
            request.setCharacterEncoding("UTF-8");
            Boolean b=rechargeRecoardOfflineLogic.add(userPhone, plateNumber, amount, payType, rechargeAdminId, roadFeeCollectorId);
            if (b){
                Result.ok(null, InfoCode.SUCCESS, response);
            }else{
                Result.ok(null, InfoCode.FAILURE, response);
            }
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@RequestParam(required = false) String beString,
                       @RequestParam(required = false) String endString,
                       @RequestParam(required = false) String rechargeCode,
                       @RequestParam(required = false) String plateNumber,
                       @RequestParam(required = false) String userphone,
                       @RequestParam(required = false, defaultValue = "1") Integer pageId,
                       @RequestParam(required = false, defaultValue = "10") Integer pageCount,
                       ModelMap modelMap,
                       HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("运营管理---线下配载费列表---/manage/rechargeOffline/list");
            request.setCharacterEncoding("UTF-8");
            PageInfo pageInfo = new PageInfo();
            pageInfo.setCurrentResult(((pageId <= 0) ? 1 : pageId - 1) * pageCount);
            pageInfo.setPageSize(pageCount);
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beString);
            params.put("endTime", StringUtils.isBlank(endString)?endString:endString+" 23:59:59");
            params.put("rechargeCode", rechargeCode);
            params.put("userPhone", userphone);
            params.put("plateNumber", plateNumber);
            pageInfo.setParams(params);
            List<RechargeRecoardOfflineVo> rechargeRecoardOfflineList = rechargeRecoardOfflineLogic.selectListByPageInfo(pageInfo);
            Object totleAmount= pageInfo.getParams().get("totleAmount");
            Map<String,Object> data=new HashMap<>();
            data.put("allAmount",totleAmount==null?0:totleAmount);
            data.put("list",rechargeRecoardOfflineList);
            data.put("pageInfo",pageInfo.build());
//            modelMap.addAttribute("rechargeRecoardOfflineList", rechargeRecoardOfflineList);
//            modelMap.addAttribute("infoCode", InfoCode.SUCCESS);
            Result.ok(data, InfoCode.SUCCESS, response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.ok(null, InfoCode.FAILURE, response);
        }
        return null;
//        return "manage/rechargeRecoard/withdrawal.list";
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(@RequestParam(required = false) String beString,
                       @RequestParam(required = false) String endString,
                       @RequestParam(required = false) String rechargeCode,
                       @RequestParam(required = false) String plateNumber,
                       @RequestParam(required = false) String userphone,
                       @RequestParam(required = false, defaultValue = "1") Integer pageId,
                       //默认为excel最大行数
                       @RequestParam(required = false, defaultValue = "1048576") Integer pageCount,
                       ModelMap modelMap,
                       HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("运营管理---线下配载费导出---/manage/rechargeOffline/export");
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
            String fileName = "";
            File file = new File(ctxPath.toString());
            if (!file.exists()) {
                file.mkdir();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setCurrentResult(((pageId <= 0) ? 1 : pageId - 1) * pageCount);
            pageInfo.setPageSize(pageCount);
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beString);
            params.put("endTime", StringUtils.isBlank(endString)?endString:endString+" 23:59:59");
            params.put("rechargeCode", rechargeCode);
            params.put("userPhone", userphone);
            params.put("plateNumber", plateNumber);
            pageInfo.setParams(params);
            List<RechargeRecoardOfflineVo> rechargeRecoardOfflineList = rechargeRecoardOfflineLogic.selectListByPageInfo(pageInfo);
            fileName= System.currentTimeMillis()+".xls";
            ExportData.exportRechargeOfflineListExcel(ctxPath + fileName, rechargeRecoardOfflineList);

            FileInputStream input=new FileInputStream(ctxPath + fileName);
            OutputStream output=response.getOutputStream();
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            byte[] b=new byte[1024*1024];
            int len=0;
            while((len=input.read(b))!=-1){
                output.write(b,0,len);
            }
            input.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ;
    }

}
